package org.looop.chuck.parser.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.looop.chuck.domain.AppInfo;
import org.looop.chuck.parser.TidyHTMLParser;
import org.looop.chuck.persistence.PersistenceManager;
import org.looop.chuck.task.URLTaskManager;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.tidy.DOMTextImpl;

public abstract class AppInfoListHTMLParser extends TidyHTMLParser {
	protected PersistenceManager persistenceManager;
	protected URLTaskManager urlTaskManager;
	
	public AppInfoListHTMLParser(PersistenceManager persistenceManager,
			URLTaskManager urlTaskManager) {
		super();
		this.persistenceManager = persistenceManager;
		this.urlTaskManager = urlTaskManager;
	}


	@Override
	public boolean onDomReady(Document root) throws Exception {
		try{
			Element rawDoc = root.getDocumentElement();
			List<AppInfo> appInfoList = extraAppInfoList(rawDoc);
			int written = persistenceManager.writeAppInfo(appInfoList);
			List<String> taskList = gernerateNewTask(rawDoc);
			urlTaskManager.addTaskList(taskList);
			return true;
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
	}
	
	protected List<Element> getElementByTagNameAndAttribute(Element rawDoc, String tagName, String attribute, String value){
		List<Element> elementList = new ArrayList<Element>();
		NodeList nodeList = rawDoc.getElementsByTagName(tagName);
		if(nodeList != null && nodeList.getLength() > 0){
			for(int i=0; i < nodeList.getLength(); i++){
				Node node = nodeList.item(i);
				if(!(node instanceof Element)){
					continue;
				}
				Element elementNode = (Element)node;
				if(StringUtils.equals(elementNode.getAttribute(attribute), value)){
					elementList.add(elementNode);
				}
			}
		}
		return elementList;
	}
	
	protected String getInnerText(Element element) {
		NodeList nodeList = element.getChildNodes();
		if(nodeList != null && nodeList.getLength() > 0){
			Node node = nodeList.item(0);
			if(node instanceof DOMTextImpl){
				return ((DOMTextImpl)node).getData();
			}
		}
		return null;
	}

	protected abstract List<AppInfo> extraAppInfoList(Element rawDoc);

	protected abstract List<String> gernerateNewTask(Element rawDoc);

}
